import 'package:flutter/material.dart';
import 'package:x3_component_core/enums/loading_status_enum.dart';
import 'package:x3_component_core/components/state_components/base_bottom_loading_component.dart';
import 'package:x3_component_core/components/state_components/base_empty_component.dart';
import 'package:x3_component_core/components/state_components/base_loading_component.dart';
import 'package:x3_component_core/components/state_components/base_nomore_component.dart';

/// 自定义下拉刷新 上拉加载的ListView
class BaseRefreshGridViewContainerComponent extends StatefulWidget {
  /// ListView的列表数量
  final int count;

  /// 是否需要上拉加载更多
  final bool needLoading;

  /// 下拉刷新的回调事件
  final Function onRefresh;

  /// 上拉加载的回调事件
  final Function onLoading;

  /// 判断当前是否是第一次进入到页码 如果是则显示中心的刷新控件
  final bool isFirstLoading;

  /// 加载更多的状态
  final LoadingStatusEnum loadingStatus;

  /// 子item的创建函数
  final IndexedWidgetBuilder builder;

  /// 是否默认加载数据
  final bool autoLoad;

  /// 获取下拉刷新的RefreshIndicatorState 通用
  final void Function(GlobalKey<RefreshIndicatorState>) getRefreshIndicatorState;

  /// 控制item间的间距
  final SliverGridDelegate gridDelegate;

  /// 构造函数
  BaseRefreshGridViewContainerComponent({
    Key key,
    @required this.count,
    @required this.builder,
    @required this.onRefresh,
    @required this.isFirstLoading,
    @required this.getRefreshIndicatorState,
    @required this.gridDelegate,
    this.autoLoad = true,
    this.needLoading = false,
    this.onLoading,
    this.loadingStatus = LoadingStatusEnum.LoadingComplete,
  }) : super(key: key);

  @override
  _BaseRefreshGridViewContainerComponentState createState() => _BaseRefreshGridViewContainerComponentState();
}

class _BaseRefreshGridViewContainerComponentState extends State<BaseRefreshGridViewContainerComponent> {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = new GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    if (widget.autoLoad == true) widget.onRefresh();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      widget.getRefreshIndicatorState(_refreshIndicatorKey);
    });
  }

  bool _onScrollNotification(ScrollNotification scrollInfo) {
    if (!widget.needLoading) return true;

    /// 当前滚动的高度
    double currentScrollPixels = scrollInfo.metrics.pixels;

    /// 最大可滚动的高度 ( 如果当前的最大可滚动高度为0 则表明当前ListView没有占满当前屏幕 )
    double maxScrollPixels = scrollInfo.metrics.maxScrollExtent;
    // 需要确保是纵向的滚动（如果逐渐内有嵌套横向滚动，横向滚动到底也会触发当前事件）
    if (scrollInfo.metrics.axis == Axis.vertical && currentScrollPixels == maxScrollPixels && maxScrollPixels != 0.0 && widget.loadingStatus == LoadingStatusEnum.LoadingComplete) {
      widget.onLoading();
    }
    return true;
  }

  /// 构建子Item项
  Widget onItemBuilder(BuildContext context, int index) {
    if (index == widget.count) {
      return _onBuildProgressIndicator();
    } else {
      return widget.builder(context, index);
    }
  }

  /// 构建底部加载更多的动画
  Widget _onBuildProgressIndicator() {
    switch (widget.loadingStatus) {
      case LoadingStatusEnum.Loading:
        return BaseBottomLoadingComponent();
        break;
      case LoadingStatusEnum.LoadingComplete:
        return null;
        break;
      case LoadingStatusEnum.NoMore:
        return BaseNoMoreComponent();
        break;
    }
    return null;
  }

  /// 构建第一次加载时的动画
  Widget _buildFirstLoadingAnimation() {
    return widget.isFirstLoading == true ? BaseLoadingComponent() : SizedBox();
  }

  /// 构建没有数据时的显示
  Widget _buildNoData() {
    return widget.isFirstLoading == false && widget.count == 0 ? BaseEmptyComponent() : SizedBox();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        _buildRefreshIndicator(),
        _buildFirstLoadingAnimation(),
      ],
    );
  }

  Widget _buildRefreshIndicator() {
    return NotificationListener<ScrollNotification>(
      onNotification: _onScrollNotification,
      child: RefreshIndicator(
        key: _refreshIndicatorKey,
        color: Theme.of(context).primaryColor,
        child: Stack(
          children: <Widget>[
            buildGridView(),
            _buildNoData(),
          ],
        ),
        onRefresh: () => widget.onRefresh(),
      ),
    );
  }

  Widget buildGridView() {
    final int count = widget.count;
    return GridView.builder(
      gridDelegate: widget.gridDelegate,
      itemBuilder: onItemBuilder,
      itemCount: count,
      physics: const AlwaysScrollableScrollPhysics(),
      // 注意这里一定要加这个属性 不然无法下拉刷新
      shrinkWrap: true,
    );
  }
}
